#-*- coding:utf-8 -*-
import os
import imp
import sys
import time
import json
import logging
import traceback
import urllib
import urllib2
import httplib
import gevent
import gevent.monkey
gevent.monkey.patch_socket()
from gevent.queue import Queue

reload(sys)
sys.setdefaultencoding('utf8')
FastpyAutoUpdate = True

def getTraceStackMsg():
    tb = sys.exc_info()[2]
    msg = ''
    for i in traceback.format_tb(tb):
        msg += i
    return msg

import pymysql
class MysqlPool():
    def __init__(self,pool_size=10,host='localhost',port=3306,user='root',passwd='123',db='ere',charset='utf8'):
        self.con_que=Queue()
        self.cur_que=Queue()
        try:
            for i in range(pool_size):
                conn=pymysql.connect(host=host,port=port,user=user,passwd=passwd,db=db,charset=charset)
                self.con_que.put(conn)
                cursor = conn.cursor(pymysql.cursors.DictCursor)
                cursor.execute("set names '%s'" % charset)
                self.cur_que.put(conn.cursor(pymysql.cursors.DictCursor))
        except Exception,e:
            print str(e) + getTraceStackMsg()

    def empty(self):
        return self.cur_que.empty()

    def get(self):
        return self.cur_que.get()

    def put(self, obj):
        self.cur_que.put(obj)



class dbsample():
    def __init__(self):
        # init here
        self.mysqlPool = MysqlPool(pool_size=2,host='10.66.126.57',port=3306,user='root',passwd='gcloud@2015',db='gcloud',charset='utf8')
        pass

    def test_mysql_pool(self, request, response_head):
        cursor = self.mysqlPool.get()

        sql = "select * from t_dir_platform_list limit 5"
        cursor.execute(sql)
        rows = cursor.fetchall()


        self.mysqlPool.put(cursor)
        res = json.dumps(rows, ensure_ascii=False).encode('utf8')

        return res

